import O1HD from "../../../engines/gameEngine";
import { level_cardCompositionCardType, level_cardCompositionE, level_cardCompositionGroupTypeE } from "../const/level_cardCompositionConst";
import level_cardComposition from "../level_cardComposition";
import level_cardComposition_card from "./level_cardComposition_card";

const {ccclass, property} = cc._decorator;

@ccclass
export default class level_cardComposition_cardGroup extends cc.Component {

    /**当前组中的所有卡牌 */
    cards:level_cardComposition_card[] = [];
    
    @property({type:cc.Node,tooltip:"锁图片"})
    lockSp:cc.Node = null;

    @property({type:cc.Node,tooltip:"可解锁图片"})
    unlockSp:cc.Node = null;

    @property({type:cc.Node,tooltip:"广告节点"})
    adNode:cc.Node = null;
    
    /**组类型 */
    groupType:level_cardCompositionGroupTypeE = level_cardCompositionGroupTypeE.normal;

    @property({type:cc.Label,tooltip:"合成文本"})
    lbTarget:cc.Label = null;

    @property({type:cc.Node,tooltip:"可合成粒子效果"})
    synsicNode:cc.Node = null;

    /**最大卡牌数量 */
    private maxLength:number = 10;
    
    /**卡牌的y间隔 */
    private cardIntervalY:number = 38;

    /**是否是锁定状态 */
    lockFlag:boolean = false;

    /**卡牌的高度 */
    cardHeight:number = 127;

    /**顶部间隔 */
    topInterval:number = 10;

    /**关卡 */
    level:level_cardComposition = null;

    color:cc.Color = null;

    onLoad(){
        this.initGroup();
    }

    setGroupType(type:level_cardCompositionGroupTypeE){
        this.groupType = type;
        this.initGroup();
    }

    initGroup(){
        this.lockSp.active = false;
        this.adNode.active = false;
        this.lockFlag = false;
        switch(this.groupType){
            case level_cardCompositionGroupTypeE.unlock:{
                this.lockFlag = true;
                this.lockSp.active = true;
                break;
            }
            case level_cardCompositionGroupTypeE.temp:{
                this.adNode.active = true;
                this.lockFlag = true;
                break;
            }
        }
    }

    bindData(level:level_cardComposition){
        this.level = level;
    }

    /**加入一张卡牌 */
    pushCard(card:level_cardComposition_card,isJudge:boolean = true,hasAni:boolean = true,soundFlag:boolean = true){
        if(!isJudge || this.checkCanPushCard(card)){
            let zindex:number = this.cards.length;
            let cardPos = this.getCardPos(this.cards.length);
            this.cards.push(card);
            card.setGroup(this);
            return this.level.pushCardAni(card.node,cardPos,hasAni,soundFlag).then(()=>{
                card.node.zIndex = zindex;
                this.synsicNode.active = this.checkCanSynthesis();
            });
        }
    }

    /**获取卡牌的相对位置 */
    getCardPos(cardIndex:number){
        let py = (( - (this.cardIntervalY * cardIndex)) - (this.cardHeight / 2)) - this.topInterval;
        let px:number = 0;
        let targetPos:cc.Vec2 = this.node.convertToWorldSpaceAR(cc.v2(px,py));
        return targetPos;
    }

    /**判断是否可以加入卡牌 */
    checkCanPushCard(card:level_cardComposition_card){
        if(this.cards.length >= this.maxLength){
            return false;
        }
        let lastCard = this.getLastCard();
        if(lastCard){
            return this.checkCardVaild(card,lastCard);
        }else{
            return true;
        }
    }

    /**删除一张卡牌 */
    spliceCard(card:level_cardComposition_card){
        let cardIndex:number = this.findCardIndex(card);
        if(cardIndex > -1){
            card.onSpliceToGroup();
            this.cards.splice(cardIndex,1);
        }
        if(this.cards.length == 0 && this.groupType == level_cardCompositionGroupTypeE.temp){
            this.checkTempGroupToBack();
        }
        this.synsicNode.active = this.checkCanSynthesis();
    }

    /**通过card找出卡牌的索引 */
    findCardIndex(card:level_cardComposition_card){
        let cardIndex:number = this.cards.findIndex((c:level_cardComposition_card)=>{
            return card.uuid == c.uuid;
        });
        return cardIndex;
    }

    spliceAllCards(){
        this.cards = [];
        this.synsicNode.active = this.checkCanSynthesis();
    }

    /**获取所有卡牌 */
    getCards(){
        return this.cards;   
    }

    /**获取最后一张卡牌 */
    getLastCard(){
        return this.cards[this.cards.length - 1];
    }

    /**获取所有可以移动的卡牌 */
    getMoveCards(){
        let card = this.getLastCard();
        if(!card){
            return this.cards;
        }
        let vaildCards:level_cardComposition_card[] = [card];
        for(let i = this.cards.length -2; i>=0; i--){
            let iCard = this.cards[i];
            if(this.checkMoveCardVaild(iCard,card)){
                vaildCards.push(iCard);
            }else{
                break;
            }
        }
        return vaildCards;
    }

    /**设置可以移动卡牌的选择*/
    setMoveCardSelect(isSelect:boolean){
        let cards = this.getMoveCards();
        for(let card of cards){
            let cs = card.getComponent(level_cardComposition_card);
            cs.setSelect(isSelect);
        }
    }

    /**卡牌合成 */
    async cardSynthesis(){
        return new Promise<boolean>(resolve=>{
            if(!this.checkCanSynthesis()){
                resolve(false);
                return;
            }
            // 合成
            let oneTime:number = 0.03;
            let targetPos:cc.Vec2 = this.cards[0].node.getPosition();
            this.cards.forEach((card:level_cardComposition_card,index:number)=>{
                let node:cc.Node = card.node;
                card.setSelect(false);
                //@ts-ignore
                cc.tween(node).delay(oneTime * this.maxLength - (index + 1) * oneTime ).to(oneTime * (index + 1) ,{position:targetPos}).call(()=>{
                    this.level.putOneCard(node);
                }).start();
            });
            this.scheduleOnce(()=>{
                this.spliceAllCards();
                resolve(true);
            },9 * oneTime);
        });
    }

    checkCanSynthesis(){
        if(this.cards.length < this.maxLength){
            return false;
        }
        let cardComposition:level_cardCompositionE = null;
        for(let i = 0; i < this.cards.length; i++){
            let card = this.cards[i];
            let cComposition = card.cardComposition;
            if(cComposition == null){
                return false;
            }
            if(cardComposition == null) cardComposition = cComposition;
            if(cComposition != cardComposition){
                return false;
            }
            if(card.cardType == level_cardCompositionCardType.query){
                return false;
            }
        }
        if(cardComposition == null){
            return false;
        }
        return true;
    }

    /**判断卡牌是否合法 */
    checkCardVaild(checkCard:level_cardComposition_card,judgeCard:level_cardComposition_card){  
        let checkType = checkCard.cardType;
        let judgeType = judgeCard.cardType;
        let checkComposition = checkCard.cardComposition;
        let judgeComposition = judgeCard.cardComposition;
        if(checkType == judgeType){
            if(checkType == level_cardCompositionCardType.normal){
                return checkComposition == judgeComposition;
            }
            return true;
        }else{
            if(checkType == level_cardCompositionCardType.universal && judgeType == level_cardCompositionCardType.normal){
                return true;
            }
            if(checkType == level_cardCompositionCardType.obstacles){
                return true;
            }
            return false;
        }
    }

    checkMoveCardVaild(checkCard:level_cardComposition_card,judgeCard:level_cardComposition_card){
        let checkType = checkCard.cardType;
        let judgeType = judgeCard.cardType;
        let checkComposition = checkCard.cardComposition;
        let judgeComposition = judgeCard.cardComposition;
        if(checkType == judgeType){
            if(checkType == level_cardCompositionCardType.normal){
                return checkComposition == judgeComposition;
            }
            return true;
        }else{
            return false;
        }
    }

    getMaxCardsLength(){
        return this.maxLength;
    }

    getCurCardsLength(){
        return this.cards.length;
    }

    setCanUnlock(){
        //设置为可解锁状态
        this.lockSp.active = false;
        this.unlockSp.active = true;
        this.unlockAni();
    }

    unlockAni(){
        cc.Tween.stopAllByTarget(this.unlockSp);
        let tween = cc.tween(this.unlockSp).to(0.2,{opacity:200}).to(0.2,{opacity:255});
        cc.tween(this.unlockSp).repeatForever(tween).start();
    }

    /**
     * 点击解锁卡槽
     */
    onBtnUnlockGroup(){
        O1HD.getManagers().soundMgr.playSound("cardComposition/click");
        this.unlockSp.active = false;
        this.lockFlag = false;
    }

    /**点击解锁临时卡槽 */
    onBtnTempGroup(){
        O1HD.getManagers().soundMgr.playSound("cardComposition/click");
        let unlockFun = ()=>{
            this.lockFlag = false;
            this.adNode.active = false;
        }
        if(O1HD.getServices().userSrv.getCoins() > 0){
            O1HD.getServices().userSrv.setCoins(-1,true);
            unlockFun();
        }else{
            O1HD.getServices().miniGameSrv.getAppApiInstance().loadAndShowVideoAd(()=>{
                unlockFun();
            },()=>{

            },null,"看广告解锁临时组");
        }
    }

    /**点击不可解锁的组 */
    onBtnLock(){

    }

    changeTempGroupToBack(){
        this.adNode.active = true;
    }

    /**
     * 判断临时组是否还原
     */
    checkTempGroupToBack(){
        let canDealGroup = this.level.getRandLeisureGroup();
        if(canDealGroup){
            let cards = this.cards.concat();
            for(let card of cards){
                this.spliceCard(card);
                canDealGroup.pushCard(card,false,true);
            }
            this.spliceCardEnd(cards);
            canDealGroup.pushCardEnd(cards);
            this.changeTempGroupToBack();
        }
    }

    /**设置target文本 */
    setTargetLb(targetText:string){
        this.lbTarget.string = targetText;
    }

    changeState(){
        let cards = this.getCards();
        for(let i=0; i<cards.length; i++){
            let card = cards[i];
            if(card.cardType == level_cardCompositionCardType.query){
                let isVaild:boolean = true;
                for(let j = i + 1; j<cards.length; j++){
                    let c = cards[j];
                    if(c.cardType != level_cardCompositionCardType.query){
                        isVaild = false;
                        break;
                    }
                }
                if(isVaild){
                    for(let j = i; j<cards.length; j++){
                        let c = cards[j];
                        c.cardToflip();
                    }
                }
            }
        }
    }

    pushCardEnd(cards:level_cardComposition_card[]){
        cards.forEach((card)=>{
            card.onPushToGroup();
        });
    }

    spliceCardEnd(cards:level_cardComposition_card[]){
        cards.forEach((card)=>{
            card.onSpliceToGroup();
        });
    }

}
